﻿using Nop.Core;
using Nop.Core.Domain.Messages;
using Nop.Core.Infrastructure;
using Nop.Services.Logging;
using Nop.Services.Messages;
using SpotsHub.Gateway.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace SpotsHub.Gateway.Controllers
{
    public class MessageController : Controller
    {
        private readonly IQueuedEmailService _queuedEmailService;
        private readonly IEmailAccountService _emailAccountService;

        private readonly EmailAccountSettings _emailAccountSettings;

        public MessageController(
            IQueuedEmailService queuedEmailService,
            IEmailAccountService emailAccountService,
            EmailAccountSettings emailAccountSettings
            )
        {
            this._queuedEmailService = queuedEmailService;
            this._emailAccountService = emailAccountService;
            this._emailAccountSettings = emailAccountSettings;
        }

        public ActionResult SneakPeek()
        {
            return View();
        }

        public ActionResult SellWithUs()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SellWithUs(ContactInformationModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    SendEmail(model);
                }
                return RedirectToAction("Index", "Home");
            }
            catch (Exception e)
            {
                if (ViewData["error"] == null)
                    ViewData["error"] = new List<string>();
                ((List<string>)ViewData["error"]).Add(e.ToString());

            }

            return View(model);
        }

        private void SendEmail(ContactInformationModel model)
        {
            if (String.IsNullOrWhiteSpace(model.Email))
                throw new NopException("Customer email is empty");
            if (!CommonHelper.IsValidEmail(model.Email))
                throw new NopException("Customer email is not valid");

            var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
            if (emailAccount == null)
                emailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault();
            if (emailAccount == null)
                throw new NopException("Email account can't be loaded");

            var email = new QueuedEmail()
            {
                Priority = 5,
                EmailAccountId = emailAccount.Id,
                FromName = emailAccount.DisplayName,
                From = emailAccount.Email,
                ToName = model.ContactPerson,
                To = "express@spotshub.com", // TODO: Change to sales email address
                Subject = "New contact information is submitted on Sale with Us",
                Body = GenerateMessage(model),
                CreatedOnUtc = DateTime.UtcNow,
            };
            _queuedEmailService.InsertQueuedEmail(email);

            var logger = EngineContext.Current.Resolve<ILogger>();

            logger.Information("Sale with us: " + GenerateMessage(model));
        }

        private string GenerateMessage(ContactInformationModel model)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("Business Name: {0} \n\r", model.BussinessName);
            sb.AppendFormat("Business Type: {0} \n\r", model.BussinessType);
            sb.AppendFormat("Contact Person: {0} \n\r", model.ContactPerson);
            sb.AppendFormat("Email: {0} \n\r", model.Email);
            sb.AppendFormat("Phone: {0} \n\r", model.PhoneNumber);
            return sb.ToString();
        }
    }
}
